package com.anli1.service.impl;

import com.anli1.entity.pojo.Coupon;
import com.anli1.entity.pojo.CouponRedemption;
import com.anli1.entity.vo.R;
import com.anli1.mapper.CouponRedemptionMapper;
import com.anli1.service.ICouponRedemptionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2024-10-05
 */
@Service
public class CouponRedemptionServiceImpl extends ServiceImpl<CouponRedemptionMapper, CouponRedemption> implements ICouponRedemptionService {
@Autowired
    RedisTemplate redisTemplate;
@Resource(name = "Lua_test01")
  DefaultRedisScript<Integer> seizeCouponScript;
    @Override
    public R qiangjuan(CouponRedemption coupon) {
        String userId = (String) RequestContextHolder.getRequestAttributes().getAttribute("userId", RequestAttributes.SCOPE_REQUEST);
        if (userId == null) {
            return R.error("用户id不能为空");
        }
        coupon.setUserId(userId);
        if (coupon.getCouponId() == null) {
            return R.error("活动查询失败");
        }
        //查询活动是否开始
        //  redisTemplate.opsForValue().set("coupon"+coupon.getCouponCode().toString(), coupon);
        Object o= redisTemplate.opsForValue().get("coupon"+coupon.getCouponId().toString());
       if(o==null)
       {
           return R.error("活动查询失败");
       }
        Coupon coupon2 = new Coupon();
        coupon2 = (Coupon) o;
        if (coupon2.getStatus() == 0) {
            return R.error("活动未开始");
        }
        LocalDateTime now = LocalDateTime.now();
        Date nowDate = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());

        if (nowDate.before(coupon2.getStartTime())) {
            return R.error("活动未开始");
        } else if (nowDate.after(coupon2.getEndTime())) {
            return R.error("活动已结束");
        }
        if (coupon2.getTotalStock() <= 0)
        {
            return R.error("库存不足");
        }
        // 同步队列redisKey
// 存储到 Redis

        // 资源库存redisKey
        int index = (int) (coupon2.getId() % 10);
        //任务库存队列
        String resourceStockRedisKey = String.format("Stock:%s", index);
        //同步队列redisKey
        String couponSeizeSyncRedisKey = String.format("ying:%s", index);
        // 抢券成功列表
        String couponSeizeListRedisKey = String.format("yingying%s%s",coupon.getCouponId(), index);
        /*
        用户id
        优惠卷id
         */
        List<String> list=new ArrayList<>();
        list.add(couponSeizeSyncRedisKey);// 同步队列redisKey
        list.add(resourceStockRedisKey); // 资源库存redisKey
        list.add(couponSeizeListRedisKey); // 抢券成功列表
        Long  CouponId= Long.valueOf(coupon.getCouponId());



        //开始抢卷
         Object execute=redisTemplate.execute(seizeCouponScript,list,CouponId, Long.valueOf(userId));

        return R.success(execute);
    }
}
